﻿// See https://aka.ms/new-console-template for more information
using Config1;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

/**
 *  读取配置的时候,DI要声明IOptions<T>、IOptionsMonitor<T>、IOptionsSnapshot<T>等类型
 * IOptions<T>:不会读取到配置文件更新后新的值
 * IOptionsMonitor<T>:会读取到配置文件更新后新的值
 * IOptionsSnapshot<T>:会读取到配置文件更新后新的值,会在同一个范围内(比如ASP.NET core一个请求中)保持一致.建议用IOptionsSnapshot
 */


ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile("config.json",optional:false,reloadOnChange:true);

IConfigurationRoot configRoot =builder.Build();

ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<TestController>();
serviceCollection.AddScoped<Test2>();
//把Config对象绑定到根节点上去
//serviceCollection.AddOptions().Configure<Config>(a=> configRoot.Bind(a));
//把Proxy对象绑定到proxy节点上去
//serviceCollection.Configure<Proxy>(a=>configRoot.GetSection("proxy").Bind(a));

//可以链式配置
serviceCollection
    .Configure<Config>(a=>configRoot.Bind(a))
    .Configure<Proxy>(a=>configRoot.GetSection("proxy").Bind(a));

using (ServiceProvider sp = serviceCollection.BuildServiceProvider())
{
    while (true)
    {
        using (IServiceScope scope=sp.CreateScope())
        {
            var c = scope.ServiceProvider.GetRequiredService<TestController>();
            c.Test();

            var c2 = scope.ServiceProvider.GetRequiredService<Test2>();
            c2.Test();
        }

        Console.WriteLine("点击任意键继续");
        Console.ReadKey();
    }

}








